package com.zking.service.impl;

import com.zking.dao.domain.SysResources;
import com.zking.dao.domain.SysRole;
import com.zking.dao.domain.SysUser;
import com.zking.dao.domain.SysUserRole;
import com.zking.dao.mapper.SysResourcesMapper;
import com.zking.dao.mapper.SysRoleMapper;
import com.zking.dao.mapper.SysUserMapper;
import com.zking.dao.mapper.SysUserRoleMapper;
import com.zking.service.UserService;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class UserServiceImpl implements UserService {
    @Autowired(required = false)
    private SysUserMapper userMapper;

    @Autowired(required = false)
    private SysResourcesMapper sysResourcesMapper;

    @Autowired(required = false)
    private SysRoleMapper sysRoleMapper;

    @Autowired(required = false)
    private SysUserRoleMapper sysUserRoleMapper;


    @Override
    public SysUser getUser(SysUser user) {
        //SysUser info = userMapper.selectOne(user);
        SysUser info = userMapper.findUserByUsername(user);
        return info;
    }

    @Override
    public Set<String> findPermissionsByUserId(int userId) {
        Set<String> permissions = sysResourcesMapper.findRoleNameByUserId(userId);
        Set<String> result = new HashSet<>();
        for (String permission : permissions) {
            if (StringUtils.isBlank(permission)) {
                continue;
            }
            permission = StringUtils.trim(permission);
            permission = permission.replaceAll("[\\/\\\\]", ":");
            permission = permission.substring(1);
            result.addAll(Arrays.asList(permission));
            //result.addAll(Arrays.asList(permission.split("\\s*;\\s*")));
        }
        return result;
    }

    @Override
    public List<SysResources> findPermissions() {
        List<SysResources> resources = sysResourcesMapper.selectAll();
        return resources;
    }

    @Override
    public List<SysRole> findRoles() {
        return sysRoleMapper.selectAll();
    }

    @Override
    public List<SysResources> findPermissionsByRoleId(Integer roleId) {
        return sysResourcesMapper.findPermissionsByRoleId(roleId);
    }

    @Override
    public boolean addUser(SysUser sysUser) {
        return userMapper.insert(sysUser) > 0;
    }

    @Override
    public List<SysUser> findUsers() {
        return userMapper.selectAll();
    }

    @Override
    public boolean updateUserByLock(Integer userId, Integer userEnable) {
        return userMapper.updateUserByLock(userId, userEnable);
    }

    @Override
    public boolean addUserRole(SysUserRole userRole) {
        return sysUserRoleMapper.insert(userRole) > 0;
    }

    @Override
    public boolean deleteUserRole(SysUserRole userRole) {
        return sysUserRoleMapper.delete(userRole) > 0;
    }

}
